<template>
  <div class="card">
    <div class="top">
      <a-input
        class="inputStyle"
        v-model="formData.search.user_phone"
        :allowClear="true"
        placeholder="用户手机"
      ></a-input>
      <a-input
        v-model="formData.search.user_realname"
        class="inputStyle"
        :allowClear="true"
        placeholder="用户姓名"
      ></a-input>
      <a-range-picker
        v-model="formData.search.end_date_range"
        style="margin-right: 10px; width: 350px"
        :placeholder="['申请开始时间', '申请结束时间']"
        @change="onChange"
        :show-time="{ format: 'HH:mm' }"
        format="YYYY-MM-DD HH:mm:ss"
      />
      <a-select v-model="formData.search.intermediary" :allowClear="true" placeholder="中介托管" class="inputStyle">
        <a-select-option v-for="item in trusteeship" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
      <a-select
        v-model="formData.search.repayment_plan_status"
        :allowClear="true"
        placeholder="子计划状态"
        class="inputStyle"
      >
        <a-select-option v-for="item in cidPlan" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
    </div>
    <div class="center">
      <a-select v-model="formData.search.channel_id" :allowClear="true" placeholder="计划通道" class="inputStyle">
        <a-select-option v-for="item in planType" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
      <a-select v-model="formData.search.bank_name" :allowClear="true" placeholder="银行名称" class="inputStyle">
        <a-select-option v-for="item in bankType" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
      <a-range-picker
        v-model="formData.search.repayment_plan_ctime"
        style="margin-right: 10px; width: 350px"
        :placeholder="['小计划开始时间', '小计划结束时间']"
        @change="ctimeChange"
        :show-time="{ format: 'HH:mm' }"
        format="YYYY-MM-DD HH:mm:ss"
      />
      <a-date-picker v-model="formData.search.end_date" @change="emd_dataChange" class="inputStyle" />
      <a-input
        v-model="formData.search.repayment_plan_order_sn"
        placeholder="订单编号"
        :allowClear="true"
        class="inputStyle"
      ></a-input>
    </div>
    <div class="bottom">
      <a-select v-model="formData.search.status" :allowClear="true" placeholder="计划状态" class="inputStyle">
        <a-select-option v-for="item in statusType" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
      <a-select v-model="formData.search.search_tmpl" :allowClear="true" placeholder="快捷查询" class="inputStyle">
        <a-select-option v-for="item in quickType" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
      <a-select
        v-model="formData.search.mode"
        :allowClear="true"
        placeholder="模式"
        style="margin-right: 10px; width: 170px"
      >
        <a-select-option v-for="item in modeType" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
      <a-select
        v-model="formData.search.all_brand"
        :allowClear="true"
        placeholder="是否全部品牌"
        style="margin-right: 10px; width: 170px"
      >
        <a-select-option v-for="item in allType" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
      <a-button class="btnStyle" type="danger" @click="batchEdit">批量修改</a-button>
      <a-button class="btnStyle" type="primary" @click="changeChannel">更换通道</a-button>
      <a-button class="btnStyle" type="primary" @click="loser">启动失败计划</a-button>
      <a-button class="btnStyle" type="primary" @click="query">查询</a-button>
      <a-button @click="reset()">重置</a-button>
    </div>
    <a-table
      :rowKey="(record, index) => index"
      :pagination="{
        pageSize: formData.page_size,
        pageSizeOptions: ['20', '30', '40', '50'],
        size: 'small',
        showSizeChanger: true,
        showQuickJumper: true,
        total: total,
        current: formData.page,
        showTotal: total => `共 ${total} 条`
      }"
      @change="paginChange"
      style="border: 1px solid #e8e8e8"
      show-size-changer
      show-quick-jumper
      :row-selection="rowSelection"
      :loading="loading"
      :data-source="tableData"
      :columns="columns"
    >
      <div slot="type" slot-scope="text, record">
        <span style="white-space: normal">{{ record.info }}</span>
      </div>
      <div slot="money" slot-scope="text, record">
        <span class="linkStyle" disabled @click="viewMoney(record.id)">{{
          `${record.money ? record.money : '查看余额'}`
        }}</span>
      </div>
      <div slot="mode" slot-scope="text, record">
        <a-tag :color="Color(record.mode, 1)"> {{ record.mode | modeFilter }} </a-tag>
      </div>
      <div slot="bankName" slot-scope="text, record">
        <span>{{ record.user_credit_card.bank_name }}</span>
      </div>
      <div slot="date" slot-scope="text, record">
        <span>{{ `${record.plan_start_date}~${record.plan_end_date}` }}</span>
      </div>
      <div slot="status" slot-scope="text, record">
        <span @click="viewDetail(record.id)" :style="`color: ${Color(record.status, 2)};cursor: pointer;`">
          {{ record.status | statusFilter }}
        </span>
      </div>
      <div slot="operate" slot-scope="text, record">
        <span class="linkStyle" @click="changeContent(record.id)">切换 / 1</span>
        <span class="lineStyle" style="margin: 0">丨</span>
        <span class="linkStyle" @click="showRecord">记录</span>
        <span class="lineStyle" style="margin: 0">丨</span>
        <span class="linkStyle" style="color: #008000" @click="start(record.id)">启动</span>
        <span class="lineStyle" style="margin: 0">丨</span>
        <span class="linkStyle" style="color: #ff0000" @click="cancel(record.id)">取消</span>
      </div>
    </a-table>
    <a-modal
      v-model="isShowChannel"
      wdith="40%"
      title="更换通道"
      ok-text="确认"
      cancel-text="取消"
      @cancel="hideModal"
      @ok="handleOk"
    >
      <span>通道：</span>
      <a-select style="width: 400px" v-model="channelValue" :allowClear="true" placeholder="请选择通道">
        <a-select-option v-for="item in planType" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
      </a-select>
    </a-modal>
    <BatchEdit :isShowEdit.sync="isShowEdit" :ids.sync="ids" @upload="getList" />
    <RecordList :isShowRecord.sync="isShowRecord" />
  </div>
</template>

<script>
import BatchEdit from './dialog/BatchEdit'
import RecordList from './dialog/RecordList'
let that
import {
  getPlanAPI,
  getTypeAPI,
  getTimeListAPI,
  startLoserAPI,
  changeChannlAPI,
  startAPI,
  cancelAPI,
  getMoneyAPI
} from '@/api/transaction.js'
import { getBankListAPI } from '@/api/userinfo.js'
export default {
  name: 'TransactionList',
  components: {
    BatchEdit,
    RecordList
  },
  filters: {
    modeFilter: params => that.modeType.find(item => item.id == params).name,
    statusFilter: params => that.statusType.find(item => item.id == params).name
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.select_rows = selectedRows
        }
      }
    }
  },
  data() {
    return {
      isShowRecord: false,
      ids: undefined,
      isShowEdit: false,
      isShowChannel: false,
      channelValue: '',
      total: 0,
      selectedRowKeys: [],
      select_rows: [],
      loading: false,
      formData: {
        brand_id: process.env.VUE_APP_BRAND_ID,
        page: 1,
        page_size: 20,
        search: {
          bank_name: undefined, // 银行名称
          end_date: '', // 结束时间
          repayment_plan_status: undefined, // 子计划状态
          intermediary: undefined, // 中介托管
          end_date_range: [], // 申请时间
          search_tmpl: 2, // 快捷查询
          repayment_plan_ctime: [], // 小计划时间
          repayment_plan_order_sn: '', // 订单编号
          user_phone: '', // 用户手机
          user_realname: '', // 用户姓名
          channel_id: undefined, //计划通道
          all_brand: undefined, // 全部品牌
          status: undefined, // 计划状态
          mode: undefined // 模式
        }
      },
      planType: [],
      trusteeship: [
        { id: '1', name: '中介' },
        { id: '2', name: '托管' },
        { id: '0', name: '全部' }
      ],
      modeType: [
        { id: 'novice', name: '新手', color: 'green' },
        { id: 'custom', name: '自定义', color: 'blue' },
        { id: 'empty', name: '空卡', color: 'purple' },
        { id: 'urgent', name: '应急', color: 'red' }
      ],
      allType: [{ id: '1', name: '全部品牌' }],
      cidPlan: [],
      quickType: [],
      statusType: [],
      bankType: [],
      columns: [
        {
          title: '#',
          dataIndex: 'id',
          align: 'center'
        },
        {
          title: '真实姓名',
          dataIndex: 'realname',
          align: 'center'
        },
        {
          title: '电话',
          dataIndex: 'phone',
          align: 'center'
        },
        // {
        //   title: '类型',
        //   align: 'center',
        //   scopedSlots: { customRender: 'type' }
        // },
        {
          title: '模式',
          align: 'center',
          scopedSlots: { customRender: 'mode' }
        },
        {
          title: '计划金额',
          dataIndex: 'amount',
          align: 'center'
        },
        {
          title: '未还金额',
          dataIndex: 'waiting_repayment_amount',
          align: 'center'
        },
        {
          title: '银行名称',
          align: 'center',
          scopedSlots: { customRender: 'bankName' }
        },
        {
          title: '余额名称',
          align: 'center',
          scopedSlots: { customRender: 'money' }
        },
        {
          title: '计划日期',
          align: 'center',
          scopedSlots: { customRender: 'date' }
        },
        // {
        //   title: '申请时间',
        //   dataIndex: 'ctime',
        //   align: 'center'
        // },
        {
          title: '通道名称',
          dataIndex: 'channel_name',
          align: 'center'
        },
        {
          title: '订单状态',
          align: 'center',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '原因',
          align: 'center',
          width: '140px',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '操作',
          align: 'center',
          width: '150px',
          scopedSlots: { customRender: 'operate' }
        }
        // {
        //   title: '短信',
        //   dataIndex: 'is_send_sms_txt',
        //   align: 'is_send_sms_txt'
        // }
      ],
      tableData: []
    }
  },
  created() {
    that = this
    this.getInfoList()
  },
  methods: {
    query() {
      this.formData.page = 1
      this.getInfoList()
    },
    Color(params, sign) {
      if (sign === 1) return that.modeType.find(item => item.id == params).color
      if (sign === 2)
        return params == -30
          ? '#e70606'
          : `${
              params == 15
                ? '#3f1fff'
                : `${
                    params == 20
                      ? '#1e90ff'
                      : `${params == 10 || params == 30 ? '#00d98f' : `${params == -20 ? '#fccb21' : ''}`}`
                  }`
            }`
    },
    async getInfoList() {
      const array = [
        getPlanAPI({ brand_id: process.env.VUE_APP_BRAND_ID, search: { type: 1 } }),
        getTypeAPI({ brand_id: process.env.VUE_APP_BRAND_ID }),
        getBankListAPI({ brand_id: process.env.VUE_APP_BRAND_ID, search: { from: 'repayment' } })
      ]
      this.getList()
      const [getPlan, getType, getBankList] = await Promise.all(array)
      this.planType = getPlan.data
      this.cidPlan = getType.data.repayment_plan_status
      this.quickType = getType.data.search_tmpl
      this.statusType = getType.data.status
      this.bankType = getBankList.data
    },
    async getList() {
      try {
        this.loading = true
        const { data } = await getTimeListAPI(this.formData)
        this.tableData = data.list.map(item => {
          item.disabled = false
          return item
        })
        this.total = data.total
      } finally {
        this.loading = false
      }
    },
    onChange(date, value) {
      this.formData.search.end_date_range = value
    },
    emd_dataChange(date, value) {
      this.formData.search.repayment_plan_ctime = value
    },
    ctimeChange(date, value) {
      this.formData.search.repayment_plan_ctime = value
    },
    reset() {
      this.formData = {
        brand_id: process.env.VUE_APP_BRAND_ID,
        page: 1,
        page_size: 20,
        search: {
          bank_name: undefined, // 银行名称
          end_date: '', // 结束时间
          repayment_plan_status: undefined, // 子计划状态
          intermediary: undefined, // 中介托管
          end_date_range: [], // 申请时间
          search_tmpl: 2, // 快捷查询
          repayment_plan_ctime: [], // 小计划时间
          repayment_plan_order_sn: '', // 订单编号
          user_phone: '', // 用户手机
          user_realname: '', // 用户姓名
          channel_id: undefined, //计划通道
          all_brand: undefined, // 全部品牌
          status: undefined, // 计划状态
          mode: undefined // 模式
        }
      }
      this.getList()
    },
    paginChange(value) {
      console.log(value)
      this.formData.page = value.current
      this.formData.page_size = value.pageSize
      this.getList()
    },
    viewDetail(id) {
      this.$router.push({ path: 'plandetails', query: { id } })
    },
    changeChannel() {
      if (this.select_rows.length < 1) return this.$message.error('至少选择一条数据')
      this.channelValue = this.planType && this.planType[0]?.id
      this.isShowChannel = true
    },
    hideModal() {
      this.isShowChannel = false
    },
    async handleOk() {
      const id = this.select_rows.map(item => item.id)
      try {
        await changeChannlAPI({ brand_id: process.env.VUE_APP_BRAND_ID, channel_id: this.channelValue, ids: id })
        this.getList()
        this.$message.error('操作成功')
      } catch (error) {
        this.$message.error(error.data.msg)
      }
    },
    loser() {
      if (this.select_rows.length < 1) return this.$message.error('至少选择一条数据')
      this.$confirm({
        title: '您确定要启动还款失败计划吗?',
        onOk: async () => {
          try {
            const ids = this.select_rows.map(item => item.id)
            await startLoserAPI({ ids })
            this.getList()
            this.$message.success('操作成功')
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        onCancel() {
          return
        }
      })
    },
    batchEdit() {
      if (this.select_rows.length < 1) return this.$message.error('至少选择一个计划')
      this.ids = this.select_rows.map(item => item.id)
      this.isShowEdit = true
    },
    async changeContent(id) {
      try {
        await changeChannlAPI({ brand_id: process.env.VUE_APP_BRAND_ID, ids: id })
        this.$message.success('操作成功')
        this.getList()
      } catch (error) {
        this.$message.error(error.data.msg)
      }
    },
    showRecord() {
      this.isShowRecord = true
    },
    start(id) {
      this.$confirm({
        title: '确定要启动此计划吗？',
        content: h => <div style="color:red">此操作不可撤回</div>,
        icon: h => <span></span>,
        onOk: async () => {
          try {
            await startAPI({ brand_id: process.env.VUE_APP_BRAND_ID, plan_id: id })
            this.$message.success('操作成功')
            this.getList()
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        onCancel: () => {
          return
        },
        class: 'test'
      })
    },
    cancel(id) {
      this.$confirm({
        title: '确定要取消此计划吗？',
        content: h => <div style="color:red">此操作不可撤回</div>,
        icon: h => <span></span>,
        onOk: async () => {
          try {
            await cancelAPI({ brand_id: process.env.VUE_APP_BRAND_ID, plan_id: id })
            this.$message.success('操作成功')
            this.getList()
          } catch (error) {
            this.$message.error(error.data.msg)
          }
        },
        onCancel: () => {
          return
        },
        class: 'test'
      })
    },
    async viewMoney(id) {
      try {
        this.loading = true
        const result = await getMoneyAPI({ id })
        this.tableData.map(item => {
          if (item.id == id) {
            item.money = result.data.amount
          }
          return item
        })
        this.$message.success('查询成功')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-table-body {
  white-space: nowrap;
  width: 100%;
  overflow-x: auto;
  font-size: 14px;
}

/* 整个滚动条 */
/deep/ .ant-table-body::-webkit-scrollbar {
  width: 5px;
  height: 6px;
}

/deep/ .ant-table-body::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: #1890ff;
}

/deep/ .ant-table-body::-webkit-scrollbar-track {
  border-radius: 1px;
  background: #f1f1f1;
}

.center {
  margin: 10px 0;
}
.inputStyle {
  margin-right: 10px;
  width: 200px;
}
.btnStyle {
  margin-right: 10px;
}
.top,
.center,
.bottom {
  display: flex;
}
.bottom {
  margin-bottom: 20px;
}
</style>
